#include "thttpd.h"
#include "list.h"
#include "cJSON.h"
#include "common.h"

// 外部引用链表头
extern struct list_head head;

int main(int argc, char const *argv[])
{
    // 读取JSON文件
    FILE *file = fopen("modbus_config.json", "r");
    if (file == NULL) {
        perror("file fopen err\n");
        return -1;
    }

    char buf[4096] = {0};
    size_t len = fread(buf, 1, 4096, file);
    if (len <= 0) {
        perror("fread err\n");
        fclose(file);
        return -1;
    }
    fclose(file);

    // 解析JSON根节点
    cJSON *root = cJSON_Parse(buf);
    if (root == NULL) {
        printf("root err\n");
        return -1;
    }

    // 获取Modbus设备配置
    cJSON *mb_dev = cJSON_GetObjectItem(root, "mb_dev");
    if (mb_dev == NULL) {
        printf("mb_dev file\n");
        cJSON_Delete(root);
        return -1;
    }

    cJSON *ip = cJSON_GetObjectItem(mb_dev, "addr");
    cJSON *port = cJSON_GetObjectItem(mb_dev, "port");
    if (!ip || !port) {
        printf("ip or port input err\n");
        cJSON_Delete(root);
        return -1;
    }

    // 获取modbus下的data数组
    cJSON *modbus = cJSON_GetObjectItem(root, "modbus");
    if (modbus == NULL) {
        printf("modbus err\n");
        cJSON_Delete(root);
        return -1;
    }

    cJSON *data = cJSON_GetObjectItem(modbus, "data");
    if (data == NULL) {
        printf("data err\n");
        cJSON_Delete(root);
        return -1;
    }

    // 初始化链表头
    INIT_LIST_HEAD(&head);

    // 遍历data数组并填充链表
    int count = cJSON_GetArraySize(data);
    for (int i = 0; i < count; i++) {
        cJSON *item = cJSON_GetArrayItem(data, i);
        if (item == NULL) {
            printf("警告: 第 %d 项为空\n", i + 1);
            continue;
        }

        // 创建链表节点
        struct mb_node_list *node = (struct mb_node_list *)malloc(sizeof(struct mb_node_list));
        if (node == NULL) {
            perror("malloc failed");
            continue;
        }

        // 解析JSON数据
        cJSON *keyItem = cJSON_GetObjectItem(item, "key");
        cJSON *addrItem = cJSON_GetObjectItem(item, "addr");
        cJSON *nameItem = cJSON_GetObjectItem(item, "name");
        cJSON *typeItem = cJSON_GetObjectItem(item, "type");

        if (keyItem && addrItem && nameItem && typeItem) {
            node->node.key = keyItem->valueint;
            node->node.addr = addrItem->valueint;
            node->node.type = typeItem->valueint;
            strncpy(node->node.name, nameItem->valuestring, sizeof(node->node.name) - 1);
            node->node.name[sizeof(node->node.name) - 1] = '\0';

            // 添加到链表
            list_add_tail(&node->list, &head);
             printf("添加节点: key=%d, addr=%d, name=%s, type=%d\n",
                    node->node.key, node->node.addr, node->node.name, node->node.type);
        } else {
            free(node);
            printf("警告: 第 %d 项数据不完整\n", i + 1);
        }
    }

    // 初始化Modbus连接
    modbus_t *ctx = modbus_new_tcp(ip->valuestring, port->valueint);
    if (ctx == NULL) {
        perror("modbus new tcp error");
        cJSON_Delete(root);
        return -1;
    }
    modbus_set_slave(ctx, 1);
    if (modbus_connect(ctx) < 0) {
        perror("modbus connect error");
        modbus_free(ctx);
        cJSON_Delete(root);
        return -1;
    }
    printf("Modbus连接成功\n");
    putchar(10);

    // 创建数据采集线程
    pthread_t tid,tid1;
    if (pthread_create(&tid, NULL, dataacquisition, ctx) < 0) {
        perror("create_datacj err");
        modbus_free(ctx);
        cJSON_Delete(root);
        return -1;
    }
    if (pthread_create(&tid1, NULL, commandprocessing, ctx) < 0) {
        perror("create_kz err");
        modbus_free(ctx);
        cJSON_Delete(root);
        return -1;
    }

    // 等待子线程结束
    pthread_join(tid, NULL);
    pthread_join(tid1,NULL);

    // 清理资源
    modbus_free(ctx);
    cJSON_Delete(root);

    // 释放链表内存
    struct list_head *pos, *n;
    list_for_each_safe(pos, n, &head) {
        struct mb_node_list *node = list_entry(pos, struct mb_node_list, list);
        list_del(pos);
        free(node);
    }

    return 0;
}